package com.igrowing.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.igrowing.springbootinit.annotation.AuthCheck;
import com.igrowing.springbootinit.biMQ.BiProducer;
import com.igrowing.springbootinit.common.BaseResponse;
import com.igrowing.springbootinit.common.DeleteRequest;
import com.igrowing.springbootinit.common.ErrorCode;
import com.igrowing.springbootinit.common.ResultUtils;
import com.igrowing.springbootinit.constant.CommonConstant;
import com.igrowing.springbootinit.constant.UserConstant;
import com.igrowing.springbootinit.exception.BusinessException;
import com.igrowing.springbootinit.exception.ThrowUtils;
import com.igrowing.springbootinit.manager.AiManager;
import com.igrowing.springbootinit.manager.RedisLimiterManager;
import com.igrowing.springbootinit.model.dto.chart.*;
import com.igrowing.springbootinit.model.entity.Chart;
import com.igrowing.springbootinit.model.entity.User;
import com.igrowing.springbootinit.model.vo.BiResponse;
import com.igrowing.springbootinit.service.ChartService;
import com.igrowing.springbootinit.service.UserService;
import com.igrowing.springbootinit.utils.ExcelUtils;

import com.igrowing.springbootinit.utils.SqlUtils;
import io.github.briqt.spark4j.SparkClient;
import io.github.briqt.spark4j.constant.SparkApiVersion;
import io.github.briqt.spark4j.model.SparkMessage;
import io.github.briqt.spark4j.model.SparkRequestBuilder;
import io.github.briqt.spark4j.model.SparkSyncChatResponse;
import io.github.briqt.spark4j.model.request.SparkRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiProducer biProducer;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }


    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }


    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        //todo 这只是个例子，用户输入goal和目标文件后我们需要将其拼接成如下格式

        User loginUser = userService.getLoginUser(request);
        String name = genChartByAiRequest.getName();
        //todo 分析目标/需求
        String goal = genChartByAiRequest.getGoal();
        if (genChartByAiRequest.getChartType() != null) {
            goal += "，请使用" + genChartByAiRequest.getChartType();
        }
        String chartType = genChartByAiRequest.getChartType();
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名字非空且不能过长");

        //todo 校验文件格式的大小
        long size = multipartFile.getSize(); //单位为字节
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小超过1M");
        //todo 校验文件格式，检查文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> VaildFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!VaildFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式非法，请上传xls或者xlsx文件");
        }

        //todo 给每个用户分配一个限流器
        Long userId = loginUser.getId();
        redisLimiterManager.doRateLimit("genChartByAi" + String.valueOf(userId));


        //todo 拿到Excel压缩后的csv数据
        String CsvData = ExcelUtils.genExcel(multipartFile);
        //todo 构造向AI询问的格式语句
        StringBuilder target = new StringBuilder();
        //todo 将用户的需求按格式要求拼接
        target.append("分析需求：").append("\n");
        target.append(goal).append("\n");
        //todo 插入压缩后的cvs数据
        target.append("原始数据：").append("\n");
        target.append(CsvData).append("\n");
        String finalTarget = target.toString();
        String aiResult = aiManager.getAiResult(finalTarget);
        System.out.println(aiResult);
        String[] split = aiResult.split("【【【【【");
        System.out.println(split.length + "--------------------------------");
        if (split.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI生成错误");
        }
        //todo 提取图表生成语句和分析结论
        String genChart = split[1];
        String genResult = split[2];
        //todo 将图表信息保存到数据库,这里有个问题,如果用户传入的文件很大,那就会导致CasData也很大，会给数据库存储造成一定压力.
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(CsvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        boolean save = chartService.save(chart);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图表保存失败");
        }

        //todo 返回AI处理后的数据
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(loginUser.getId());
        return ResultUtils.success(biResponse);


    }

    //@PostMapping("/gen/async")
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        //todo 这只是个例子，用户输入goal和目标文件后我们需要将其拼接成如下格式
        String s = "分析需求：\n" +
                "分析网站营收的利润增长情况\n" +
                "原始数据：\n" +
                "日期，营收，利润\n" +
                "1号，10，5\n" +
                "2号，28，10\n" +
                "3号，38，25\n" +
                "4号，15，3\n" +
                "5号，10，2";
        User loginUser = userService.getLoginUser(request);
        String name = genChartByAiRequest.getName();
        //todo 分析目标/需求
        String goal = genChartByAiRequest.getGoal();
        if (genChartByAiRequest.getChartType() != null) {
            goal += "，请使用" + genChartByAiRequest.getChartType();
        }
        String chartType = genChartByAiRequest.getChartType();
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名字非空且不能过长");

        //todo 校验文件格式的大小
        long size = multipartFile.getSize(); //单位为字节
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小超过1M");
        //todo 校验文件格式，检查文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> VaildFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!VaildFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式非法，请上传xls或者xlsx文件");
        }

        //todo 给每个用户分配一个限流器
        Long userId = loginUser.getId();
        redisLimiterManager.doRateLimit("genChartByAi" + String.valueOf(userId));


        //todo 拿到Excel压缩后的csv数据
        String CsvData = ExcelUtils.genExcel(multipartFile);
        //todo 构造向AI询问的格式语句
        StringBuilder target = new StringBuilder();
        //todo 将用户的需求按格式要求拼接
        target.append("分析需求：").append("\n");
        target.append(goal).append("\n");
        //todo 插入压缩后的cvs数据
        target.append("原始数据：").append("\n");
        target.append(CsvData).append("\n");
        String finalTarget = target.toString();

        //todo 先保存到数据库
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(CsvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        //todo 异步处理请求,建议自定义队列满了之后抛异常的情况,可能存在线程安全问题
        try {
            CompletableFuture.runAsync(() -> {

                        Chart updateChart = new Chart();
                        updateChart.setId(chart.getId());
                        updateChart.setStatus("running");
                        boolean b = chartService.updateById(updateChart);
                        if (!b) {
                            handleChartUpdateError(chart.getId(), "更新图表信息失败");
                            return;
                        }

                        String aiResult = aiManager.getAiResult(finalTarget);
                        String[] split = aiResult.split("【【【【【");
                        if (split.length < 3) {
                            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI生成错误");
                        }
                        //todo 提取图表生成语句和分析结论
                        String genChart = split[1];
                        String genResult = split[2];

                        Chart updateChartResult = new Chart();
                        updateChartResult.setId(chart.getId());
                        updateChartResult.setGenChart(genChart);
                        updateChartResult.setGenResult(genResult);
                        // todo 建议定义状态为枚举值
                        updateChartResult.setStatus("succeed");
                        boolean updateResult = chartService.updateById(updateChartResult);
                        if (!updateResult) {
                            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
                        }
                    }
                    , threadPoolExecutor);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST, "当前系统繁忙，请稍后再试");
        }

        //todo 返回AI处理后的数据
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);

    }

    //@PostMapping("/gen/async/mq")
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                        GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        //todo 这只是个例子，用户输入goal和目标文件后我们需要将其拼接成如下格式
        String s = "分析需求：\n" +
                "分析网站营收的利润增长情况\n" +
                "原始数据：\n" +
                "日期，营收，利润\n" +
                "1号，10，5\n" +
                "2号，28，10\n" +
                "3号，38，25\n" +
                "4号，15，3\n" +
                "5号，10，2";
        User loginUser = userService.getLoginUser(request);
        String name = genChartByAiRequest.getName();
        //todo 分析目标/需求
        String goal = genChartByAiRequest.getGoal();
        if (genChartByAiRequest.getChartType() != null) {
            goal += "，请使用" + genChartByAiRequest.getChartType();
        }
        String chartType = genChartByAiRequest.getChartType();
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名字非空且不能过长");

        //todo 校验文件格式的大小
        long size = multipartFile.getSize(); //单位为字节
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小超过1M");
        //todo 校验文件格式，检查文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> VaildFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!VaildFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式非法，请上传xls或者xlsx文件");
        }

        //todo 给每个用户分配一个限流器
        Long userId = loginUser.getId();
        redisLimiterManager.doRateLimit("genChartByAi" + String.valueOf(userId));

        //todo 拿到Excel压缩后的csv数据
        String CsvData = ExcelUtils.genExcel(multipartFile);
        //todo 构造向AI询问的格式语句
        StringBuilder target = new StringBuilder();
        //todo 将用户的需求按格式要求拼接
        target.append("分析需求：").append("\n");
        target.append(goal).append("\n");
        //todo 插入压缩后的cvs数据
        target.append("原始数据：").append("\n");
        target.append(CsvData).append("\n");
        String finalTarget = target.toString();

        //todo 先保存到数据库
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(CsvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        //todo 发送消息到消息队列
        Long id = chart.getId();
        biProducer.sendMessage(String.valueOf(id));

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(id);
        return ResultUtils.success(biResponse);


    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }

    /**
     * todo 定时任务，每隔一个小时扫描数据库里面处理失败的数据，重新发送给消息队列
     */

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void reMakeChart() {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "failed");
        List<Chart> failedChartList = chartService.list(queryWrapper);
        for (Chart chart : failedChartList) {
            Long id = chart.getId();
            biProducer.sendMessage(String.valueOf(id));
        }

    }


}
